package com.lee.config.shiro;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.support.SimpleValueWrapper;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Set;

@Component
public class ShiroRedisCacheManager implements CacheManager {

    private org.springframework.cache.CacheManager cacheManager;

    public org.springframework.cache.CacheManager getCacheManager() {
        return cacheManager;
    }

    @Autowired
    public void setCacheManager(org.springframework.cache.CacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }

    @Override
    public <K, V> Cache<K, V> getCache(String name) throws CacheException {
        org.springframework.cache.Cache ownCache = cacheManager.getCache(name);
        return new IntegrateCacheWrapper(ownCache);
    }

    static class IntegrateCacheWrapper implements Cache {

        private org.springframework.cache.Cache shiroCache;

        IntegrateCacheWrapper(org.springframework.cache.Cache ownCache) {
            this.shiroCache = ownCache;
        }

        @Override
        public Object get(Object key) throws CacheException {
            Object value = shiroCache.get(key);
            if (value instanceof SimpleValueWrapper) {
                return ((SimpleValueWrapper) value).get();
            }
            return value;
        }

        @Override
        public Object put(Object key, Object value) throws CacheException {
            shiroCache.put(key, value);
            return value;
        }

        @Override
        public Object remove(Object key) throws CacheException {
            shiroCache.evict(key);
            return null;
        }

        @Override
        public void clear() throws CacheException {
            shiroCache.clear();
        }

        @Override
        public int size() {
            return 0;
        }

        @Override
        public Set keys() {
            return null;
        }

        @Override
        public Collection values() {
            return null;
        }
    }
}
